import Vue from 'vue'

/**
 * 节流函数
 * @param {function} function
 * @method delayFunc()
 */
let lastScrollCall
const delayFunc = (fn) => {
	const now = new Date()
		.getTime()
	if (now - lastScrollCall < 1400) return
	lastScrollCall = now
	setTimeout(() => {
		fn()
	}, 60)
}
/**
 * 对象数组遍历
 * @param {Array,object} object
 * @callback onEach() 遍历后的函数
 */
const eachDescendentParameters = (option) => {
	const resultOption = Object.assign({
		object: undefined,
		onEach: (map, key, value) => {}
	}, option)
	const initErgodic = (map, key, value) => {
		if (value instanceof Array) {
			arrayErgodic(value)
		} else if (value instanceof Object) {
			objectErgodic(value)
		} else {
			resultOption.onEach(map, key, value)
		}
	}
	const objectErgodic = (object) => {
		for (const key in object) {
			initErgodic(object, key, object[key])
		}
	}
	const arrayErgodic = (array) => {
		array.map((item, index) => {
			initErgodic(array, index, item)
		})
	}
	initErgodic(null, null, resultOption.object)
}

/**
 *  图片上传
 *  @return {Promise}   
 */
const chooseImage = () => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original'],
			success: res => {
				uni.showLoading({
					title: '正在上传',
					mask: true
				})
				uni.uploadFile({
					url: Vue.prototype.api.upload,
					filePath: res.tempFilePaths[0],
					name: 'file',
					success: res => {
						console.log(res);
						uni.hideLoading()
						if (JSON.parse(res.data)
							.errorCode === 'hasIllegalContent') {
							reject('hasIllegalContent')
							return
						}
						resolve(JSON.parse(res.data)
							.fileUrl)
					},
					fail: () => {
						uni.hideLoading()
						uni.showToast({
							title: '图片上传失败',
							icon: 'none',
							duration: 2000
						})
					}
				})
			}
		})
	})

}
export default {
	delayFunc,
	eachDescendentParameters,
	chooseImage
}
